import 'dart:io';
import 'dart:isolate';

late List<Isolate> isolates;

class Address {
  late int start;
  late int end;
  late int host;
  late String prefix;
  late SendPort sendPort;

  Address(this.start, this.end, this.host, this.prefix, this.sendPort);
}

class Interface {
  late NetworkInterface interface;
  late SendPort sendPort;

  Interface(this.interface, this.sendPort);
}

void ping(Address p) async {
  if (p.end > 254) {
    p.end = 254;
  }
  for (var start = p.start; start <= p.end; start++) {
    if (start == p.host) {
      continue;
    }
    var current = '${p.prefix}.${start}';
    var result = await Process.run('ping', ['-n', '1', current]);
    var res = result.stdout as String;
    if (!res.contains('unreachable') &&
        !res.contains('timed out') &&
        !res.contains('无法访问') &&
        !res.contains('超时')) {
      p.sendPort.send(current);
    }
  }
  p.sendPort.send('over ${p.start} ${p.end}');
}

void start(Interface interface) async {
  isolates = List<Isolate>.empty(growable: true);
  ReceivePort receivePort = ReceivePort();

  // var ip = interfaces.first.addresses.first.address;
  var arr = interface.interface.addresses.first.address.split('.');
  var prefix = '${arr[0]}.${arr[1]}.${arr[2]}';

  for (var i = 1; i <= 254; i += 6) {
    isolates.add(await Isolate.spawn(
        ping,
        new Address(
            i, i + 5, int.parse(arr[3]), prefix, receivePort.sendPort)));
  }

  receivePort.listen((message) {
    interface.sendPort.send("${interface.interface.name} $message");
  });
}

void main() async {
  late List<Isolate> isolates = List.empty(growable: true);
  ReceivePort receivePort = ReceivePort();
  var list = await NetworkInterface.list();
  list.forEach((v) async {
    isolates.add(
        await Isolate.spawn(start, new Interface(v, receivePort.sendPort)));
  });
  var s = DateTime.now();
  print(s.toString());
  receivePort.listen((message) {
    print(message);
    print(DateTime.now().toString());
  });
}
